import {Component} from '@angular/core';
import {BaseApiComponent} from '../page-api/base-api.component';
import {MockConfig} from '../../entity/mock-config';
import {PageVoService} from '../../service/page-vo.service';
import {ActivatedRoute, Router} from '@angular/router';
import {DocService} from '../../service/doc.service';
import {MessageService} from '../../service/message.service';
import {MockService} from '../../service/mock.service';
import {AlertMessage} from '../../entity/alert-message';
import {MockConditionItem} from '../../entity/mock-condition-item';

@Component({
    selector: 'app-page-api-mock-list',
    templateUrl: './page-api-mock-list.component.html',
    styleUrls: ['./page-api-mock-list.component.css']
})
export class PageApiMockListComponent extends BaseApiComponent {

    mocks: MockConfig[] = [];

    constructor(protected pageVoService: PageVoService,
                protected activatedRoute: ActivatedRoute,
                protected router: Router,
                protected docService: DocService,
                protected messageService: MessageService,
                private mockService: MockService
    ) {
        super(pageVoService, activatedRoute, router, docService, messageService);
    }

    protected onApiReady() {
        this.mockService.list(this.docId, this.apiId).subscribe(resp => {
            if (resp.code !== 200) {
                this.messageService.add(AlertMessage.error(resp.message));
                return;
            }
            this.mocks = resp.data;
            if (this.mocks.length === 0) {
                // 跳转
                this.router.navigate(['/doc', this.docId, this.apiId, 'mock', 'new']);
            }
        });
    }

    getMockCondStr(mockConfig: MockConfig): string {
        if (!mockConfig) {
            return '--';
        }
        if (mockConfig.responseType === 1) {
            return '--';
        }
        const condition = mockConfig.restCondition;
        if (!condition) {
            return '--';
        }
        const cond = [];
        this.getParamCond('路径参数', condition.pathParams, cond);
        this.getParamCond('请求头参数', condition.headerParams, cond);
        this.getParamCond('url参数', condition.urlParams, cond);
        if (cond.length === 0) {
            return '*';
        }
        return cond.join('\n');
    }

    private getParamCond(name: string, params: MockConditionItem[], cond: string[]) {
        if (params && params.length > 0) {
            params.forEach(header => {
                if (header.available && header.key) {
                    cond.push(name + ':' + header.key + ' ' + header.operator + ' ' + header.value);
                }
            });
        }
    }

    delete(index: number) {
        const mock = this.mocks[index];
        if (!mock) {
            this.messageService.add(AlertMessage.error('Mock配置不存在或已被删除！'));
            return;
        }
        this.mockService.delete(this.docId, this.apiId, mock.id).subscribe(resp => {
            if (resp.code === 200) {
                this.messageService.add(AlertMessage.success('Mock配置删除成功！'));
                this.mocks.splice(index, 1);
            } else {
                this.messageService.add(AlertMessage.error(resp.data));
            }
        });
    }

    getMockUrl(mock: MockConfig) {
        const port = window.location.port === '80' ? '' : window.location.port;
        return `${window.location.protocol}//${window.location.host}${port}/api/mock/test/${mock.id}`;
    }
}
